package cn.classTest.mall.controller;


import cn.classTest.mall.domain.Employee;
import cn.classTest.mall.service.EmployeeService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(String username, String password, Model model, HttpSession session, ThymeleafViewResolver viewResolver) {
        try {
            //1.获取subject，调用登录方法
            Subject subject = SecurityUtils.getSubject();
            //加密
            Md5Hash md5Password = new Md5Hash(password);
            //2.创建令牌
            UsernamePasswordToken token = new UsernamePasswordToken(username, md5Password.toString());
            //3.登录
            subject.login(token);
            session.setAttribute("EMPLOYEE_IN_SESSION", subject.getPrincipal());

            return "redirect:/department/list";
        } catch (Exception e) {
            model.addAttribute("errorMsg", "账户或密码错误");
            return "forward:/static/login.html";
        }
    }

    //进入修改密码页面
    @RequestMapping("/user/input")
    public String input() {
        return "/common/user";
    }


    @RequestMapping("/user/edit")
    public String edit(Employee employee, String oldpassword, Model model) {
        //1.获取subject
        Subject subject = SecurityUtils.getSubject();
        Employee oldEmployee = (Employee) subject.getPrincipal();

        //加密
        Md5Hash md5Password = new Md5Hash(employee.getPassword());
        employee.setPassword(md5Password.toString());
        Md5Hash oldMd5 = new Md5Hash(oldpassword);
        oldpassword = oldMd5.toString();

        try {
            if (!oldEmployee.getEmail().equals(employee.getEmail())) {
                throw new RuntimeException("出现异常");
            } else if (!oldpassword.equals(oldEmployee.getPassword())) {//旧密码
                throw new RuntimeException("出现异常");
            }
            employeeService.updatePassword(employee);
            model.addAttribute("errorMsg", "请重新登陆");
        } catch (Exception e) {
            throw new RuntimeException("出现异常");

        }
        return "redirect:/logout";
    }
}
